import React, { useEffect, useState, useMemo } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import { NavBar, InfiniteScroll, PullToRefresh, Selector } from "antd-mobile";
import { ClockCircleOutline, AntOutline, BillOutline } from "antd-mobile-icons";
import http from "../../api/http";
import NavDate from "../../components/NavDate";
import styles from "./list.module.css";

function Index() {
  const navigate = useNavigate();
  const [searQuery, setSearQuery] = useSearchParams();
  const start = searQuery.get("start");
  const end = searQuery.get("end");
  const date = searQuery.get("date");
  const [page, setPage] = useState(1);
  const [trainList, setTrainList] = useState([]);
  const [hasMore, setHasMore] = useState(true);

  //请求数据的方法
  const feachList = async () => {
    const data = Object.fromEntries(searQuery);
    const res = await http.post("/xx/trip/train", { ...data, page });
    setTrainList((prev) => {
      return [...prev, ...res.data.data];
    });
    setPage((prev) => {
      return prev + 1;
    });
    if (res.data.data.length === 0) {
      setHasMore(false);
    }
  };

  useEffect(() => {
    setPage(1);
    setTrainList([]);
    setHasMore(true);
    feachList;
  }, [date, searQuery]);

  //下拉刷新
  const FreshFn = async () => {
    const data = Object.fromEntries(searQuery);
    const res = await http.post("/xx/trip/train", data);
    setTrainList(res.data.data);
    setPage(1);
  };

  //筛选车次
  const [options] = useState([
    {
      label: <ClockCircleOutline />,
      description: "出发 早 → 晚",
      value: "isDesc",
    },
    {
      label: <AntOutline />,
      description: "只看高铁动车",
      value: "isSpeed",
    },
    {
      label: <BillOutline />,
      description: "只看有票",
      value: "isSeat",
    },
  ]);

  //筛选车次
  const handelSel = async (value) => {
    //value === ["isDesc"]
    //切换出发 早 → 晚 文字
    if (value.includes("isDesc")) {
      options[0].description = "耗时 短 → 长";
    } else {
      options[0].description = "出发 早 → 晚";
    }

    //定义对象
    const obj = {
      isDesc: false,
      isSpeed: false,
      isSeat: false,
    };

    //给对象修改状态
    value.forEach((item) => {
      obj[item] = true;
    });

    //将对象的参数添加到地址拦中
    setSearQuery((prev) => {
      return { ...Object.fromEntries(prev), ...obj };
    });

    // 重新请求数据
    const data = { ...Object.fromEntries(searQuery), ...obj };
    const res = await http.post("/xx/trip/train", data);
    setTrainList(res.data.data);
    setHasMore(true);
    // 重置页码
    setPage(1);
  };

  //默认筛选状态
  const defaultSel = useMemo(() => {
    let temp = [];

    ["isDesc", "isSpeed", "isSeat"].forEach((item) => {
      if (searQuery.get(item) === "true") {
        temp.push(item);
      }
    });

    if (searQuery.get("isDesc") === "true") {
      options[0].description = "耗时 短 → 长";
    }

    return temp;
  }, [searQuery]);

  //点击列表跳转详情页
  const handelToDeatil = (item) => {
    navigate(
      `/detail/${item.id}?start=${item.startStation}&end=${item.endStation}&date=${date}`
    );
  };

  return (
    <div>
      <NavBar onBack={() => navigate("/")}>
        {start} ➡️ {end}
      </NavBar>
      <div>
        <NavDate date={date} />
      </div>
      {/* 渲染车次列表 */}
      <div>
        <PullToRefresh onRefresh={() => FreshFn()}>
          <table>
            <tbody className={styles.tableWrap}>
              {trainList.length > 0 &&
                trainList.map((item, ind) => (
                  <tr key={ind} onClick={() => handelToDeatil(item)}>
                    <td>发车 {item.startTime}</td>
                    <td>{item.startStation}</td>
                    <td>{item.trainNo}</td>
                    <td>￥{item.ssoftSeat.price}</td>

                    <td>到达 {item.endTime}</td>
                    <td>{item.endStation}</td>
                    <td>耗时 {item.timeTaken}</td>
                    <td>
                      二等座：{item.ssoftSeat.ticketNum}
                      {typeof item.ssoftSeat.ticketNum === "number" ? "张" : ""}
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </PullToRefresh>
      </div>
      <InfiniteScroll loadMore={feachList} hasMore={hasMore} />
      <div>
        <Selector
          columns={3}
          options={options}
          defaultValue={defaultSel}
          multiple
          onChange={(value) => handelSel(value)}
        />
      </div>
    </div>
  );
}

export default Index;
